﻿using System;
using System.Collections;
using System.Drawing;
using com.google.zxing;
using com.google.zxing.common;
using com.google.zxing.qrcode.decoder;

namespace com.google.zxing.helper
{
    public class QRHelper
    {
        /// <summary>
        /// 生成QR格式二维码
        /// </summary>
        /// <param name="content"></param>
        /// <param name="type"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        /// <param name="ico"></param>
        /// <returns></returns>
        public static Bitmap Create(string content, int w = 300, int h = 300, Image ico = null)
        {
            if (ico == null)
            {
                return Create(content, ErrorCorrectionLevel.H, w, h).ToBitmap();
            }
            else
            {
                return Create(content, ErrorCorrectionLevel.H, w, h).ToIcoBitMap(ico);
            }
        }

        /// <summary>
        /// 生成QR格式二维码
        /// </summary>
        /// <param name="content"></param>
        /// <param name="type"></param>
        /// <param name="erLev"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        /// <returns></returns>
        public static ByteMatrix Create(string content, ErrorCorrectionLevel erLev, int w = 300, int h = 300)
        {
            //构造二维码写码器参数
            Hashtable hint = new Hashtable();
            hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            hint.Add(EncodeHintType.ERROR_CORRECTION, erLev);
            //构造二维码写码器
            MultiFormatWriter mutiWriter = new MultiFormatWriter();
            return mutiWriter.encode(content, BarcodeFormat.QR_CODE, w, h, hint);
        }

        /// <summary>
        /// 读取QR二维码信息
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        public static string Read(Image img)
        {
            Bitmap bitimg = new Bitmap(img);
            MultiFormatReader mutiReader = new com.google.zxing.MultiFormatReader();
            LuminanceSource ls = new RGBLuminanceSource(bitimg, img.Width, img.Height);
            BinaryBitmap bb = new BinaryBitmap(new HybridBinarizer(ls));
            Hashtable hints = new Hashtable();
            hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            Result res = mutiReader.decode(bb, hints);
            return res.Text;
        }

    }
}
